app.controller("staffController",['$scope','$http','myPage','$filter', function($scope, $http, myPage,$filter){
    $scope.myPage={
        currentPage:1,//访问第几页数据，从1开始
        totalItems:0,//数据库中总共有多少条数据
        itemsPerPage: 6,//默认每页展示多少条数据，可更改
        pagesLength: 15,
        perPageOptions: [10, 20, 30, 40, 50,60]//可选择的每页展示多少条数据
    };
    //监测当页码。总数据，每页展示数据个数变化时，重新加载数据
    $scope.$watch(function ()
    {return $scope.myPage.itemsPerPage+' '+$scope.myPage.currentPage+' '+$scope.myPage.totalItems;},getList) ;
    function getList(){
        //获取列表需要时，将页码重置为1
        $scope.myPage.currentPage=myPage.pageNub;
        //传给服务器时，页码从0开始
        $http({
            method: 'POST',
            url: '/OA/staff/list',
            data: $.param({pageNumber:myPage.pageNub}),
             headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function (response) {
            $scope.datas=response.data.list;
            $scope.myPage.totalItems=response.data.totalRow;//当获取总数据后，修改默认值;
            // 定义一个空对象 , 用于更新和保存数据时临时存储
            $scope.prod = {};
            $scope.arrs=$scope.datas;
            // 定义一个单击删除按钮时触发的事件，用于删除选中行
            $scope.delete = function($index){
                if ($index>=0) {
                    if(confirm("是否删除"+$scope.arrs[$index].username+"的信息") ){
                        //将需要删除的卡号传给后台  2017/7/10
                        $http({
                            method: 'POST',
                            url: '/OA/staff/delete',
                            data: $.param({id:$scope.arrs[$index].id,loginname:$scope.arrs[$index].loginname}),
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                        }).success(function (result) {
                            if (result.ok==true) {
                                $scope.arrs.splice($index,1);
                                setTimeout(function () {
                                    window.location.reload()
                                },1)
                            }
                        }).error(function(result){
                            alert("删除失败")
                        })
                    }
                };
            }
            // 查看员工信息;
            $scope.ToView=function($index){
                $('#staffcheck').modal('show');
                $http({
                    method:"POST",
                    url:"/OA/staff/query",
                    data:$.param({id:$scope.arrs[$index].id}),
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (response){
                    console.log(response)
                    if(response.ok==true){
                        $scope.findContent=response.data;
                        if($scope.findContent.date_departure=="2000-01-01"){
                            $scope.findContent.date_departure="";
                        }
                    }
                })
            };
            // 定义一个空对象 , 用于更新和保存数据时临时存储
            $scope.prod = {};
            //定义修改modal层的班课设置
            $("input[name='updataclass']:checkbox").click(function(){
                if ($(this).is(":checked")) {
                    $(this).attr("checked", true);
                    $(this).prop('value','0');
                }else {
                    $(this).attr("checked", false);
                    $(this).prop('value','1');
                }
            });
            //定义一个单击修改按钮时触发的事件，用于单击后弹出模块窗口用于修改报课单数据
            $scope.updata = function ($index) {
                //显示bootstrap中的模块窗口
                $('#staffmodify').modal('show');
                //将选中行的数据绑定到临时对象prod中，在下面的模态窗口中展示出来
                $scope.prod.loginname = $scope.arrs[$index].loginname;
                $scope.prod.username = $scope.arrs[$index].username;
                $scope.prod.birthday = $scope.arrs[$index].birthday;
                $scope.prod.card_bank = $scope.arrs[$index].card_bank;
                $scope.prod.card_identification = $scope.arrs[$index].card_identification;
                $scope.prod.mobile = $scope.arrs[$index].mobile;
                $scope.prod.wechat = $scope.arrs[$index].wechat;
                $scope.prod.qq = $scope.arrs[$index].qq;
                $scope.prod.email = $scope.arrs[$index].email;
                $scope.prod.campus_id = $scope.arrs[$index].campus_id;
                $scope.prod.campus_name = $scope.arrs[$index].campus_name;
                $scope.prod.subject_id = $scope.arrs[$index].subject_id;
                $scope.prod.subject_name = $scope.arrs[$index].subject_name;
                $scope.prod.sex = $scope.arrs[$index].sex;
                $scope.prod.roles_name=$scope.arrs[$index].roles_name;
                $scope.prod.roles_id=$scope.arrs[$index].roles_id;
                $scope.prod.is_class=$scope.arrs[$index].is_class;
                $scope.prod.date_entry=$scope.arrs[$index].date_entry;
                $scope.prod.date_departure=$scope.arrs[$index].date_departure;
                $scope.prod.state=$scope.arrs[$index].state;
                $("#belongeschool").find("option[value="+$scope.arrs[$index].campus_id+"]").prop("selected","selected");
                $("#subjectname").find("option[value="+$scope.arrs[$index].subject_id+"]").prop("selected","selected");
                $("#updatasex").find("option[value="+$scope.arrs[$index].sex+"]").prop("selected","selected");
                $("#updatastate").find("option[value="+$scope.arrs[$index].state+"]").prop("selected","selected");
                $("#modifySex").html($scope.prod.sex);
                $("#modifySex").attr("data",$scope.prod.sex);
                $scope.prod.id=$scope.arrs[$index].id;
                $("input[name='updataclass']").prop('value',$scope.prod.is_class);
                if ($("input[name='updataclass']").attr('value')=="1") {
                    $("input[name='updataclass']").prop("checked",false);
                }else if($("input[name='updataclass']").attr('value')=="0"){
                    $("input[name='updataclass']").prop("checked",true);
                }
                // 修改后保存
                $scope.save = function () {
                    var loginname=$("#updataloginname").val();
                    var username=$("#updatausername").val();
                    var birthday=$("#updatabirthday").val();
                    var card_bank=$("#updatacard_bank").val();
                    var card_identification=$("#updatacard_identification").val();
                    var mobile=$("#updatamobile").val();
                    var wechat=$("#updatawechat").val();
                    var qq=$("#updataqq").val();
                    var email=$("#updataemail").val();
                    var campus_id=$("#belongeschool").find("option:selected").val();
                    var campus_name=$("#belongeschool").find("option:selected").html();
                    var subject_id=$("#subjectname").find("option:selected").val();
                    var subject_name=$("#subjectname").find("option:selected").text();
                    var sex=$("#updatasex").find("option:selected").val();
                    var roles_name=$("#updatarole").text();
                    var roles_id=$("#updataId").text();
                    var is_class=$("input[name='updataclass']").val();
                    var date_entry=$("#date_entry").val();
                        date_entry=date_entry.replace(/-/g,'/');
                        date_entry=new Date(date_entry);
                        date_entry=date_entry.getTime();
                        date_entry=$filter("date")(date_entry, "yyyy-MM-dd");
                    var out_entry=$("#out_entry").val();
                        if(out_entry==""){
                            out_entry="0";
                        }
                        date_departure=out_entry.replace(/-/g,'/');
                        date_departure=new Date(date_departure);
                        date_departure=date_departure.getTime();
                        date_departure=$filter("date")(date_departure, "yyyy-MM-dd");
                    var state=$("#updatastate").find("option:selected").val();
                    $scope.updataJson={loginname:loginname,username:username,mobile:mobile,sex:sex,birthday:birthday,card_identification:card_identification,card_bank:card_bank,wechat:wechat,qq:qq,email:email,date_entry:date_entry,date_departure:date_departure,is_class:is_class,campus_id:campus_id,campus_name:campus_name,roles_id:roles_id,roles_name:roles_name,id:$scope.prod.id,subject_id:subject_id,subject_name:subject_name,state:state}
                    console.log($scope.updataJson)
                    $http({
                        method:"POST",
                        url:"/OA/staff/update",
                        data:$.param($scope.updataJson),
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                    }).success(function (response) {
                        console.log(response.ok);
                        $('#staffmodify').modal('hide');
                        setTimeout(function () {
                            window.location.reload()
                        },600)
                    })
                }
            };
        })
 }
// 添加信息时验证账号
     $("#formyanzheng").validate({
        //出错时添加的标签
        errorElement: "span",
        rules: {
            loginname: {
                required: true,
                minlength: 5,
                maxlength: 16,
                remote: {
                    type: "post",
                    url: "/OA/staff/exist",
                    data: {
                        value: function() {
                            return $("#loginname").val();
                        },
                        property: function(){
                            return "loginname";
                        }
                    },
                    dataType: "html",
                    dataFilter: function(data, type) {
                        var data=JSON.parse(data); 
                        if (data.ok == false){
                            return true;
                        }
                        else if(data.ok==true){
                            return false;
                        }
                    }
                }
            }
        },
        success: function(label) {
            //正确时的样式            
        },
        messages: {
            loginname: {
                required: "请输入用户名，5-10个字符（字母、数字、下划线",
                minlength: "用户名长度不能小于5个字符",
                maxlength: "用户名长度不能大于16个字符",
                remote: "用户名不可用或用户名已被占用"
            }
        }
    });
    // 银行卡号验证
    //js正则实现用户输入银行卡号的控制及格式化
    document.getElementById("card_bank").onkeyup=function(){
        formatBankNo (this)
    };
    document.getElementById("card_bank").onkeydown=function(){
        formatBankNo (this)
    };
    document.getElementById("updatacard_bank").onkeyup=function(){
        formatBankNo (this)
    };
    document.getElementById("updatacard_bank").onkeydown=function(){
        formatBankNo (this)
    };
        function formatBankNo (BankNo){
            if (BankNo.value == "") return;
            var account = new String (BankNo.value);
            account = account.substring(0,22); /*帐号的总数, 包括空格在内 */
            if (account.match (".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}") == null){
                /* 对照格式 */
                if (account.match (".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|" + ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|" +
                        ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|" + ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}") == null){
                    var accountNumeric = accountChar = "", i;
                    for (i=0;i<account.length;i++){
                        accountChar = account.substr (i,1);
                        if (!isNaN (accountChar) && (accountChar != " ")) accountNumeric = accountNumeric + accountChar;
                    }
                    account = "";
                    for (i=0;i<accountNumeric.length;i++){    /* 可将以下空格改为-,效果也不错 */
                        if (i == 4) account = account + " "; /* 帐号第四位数后加空格 */
                        if (i == 8) account = account + " "; /* 帐号第八位数后加空格 */
                        if (i == 12) account = account + " ";/* 帐号第十二位后数后加空格 */
                        account = account + accountNumeric.substr (i,1)
                    }
                }
            }
            else
            {
                account = " " + account.substring (1,5) + " " + account.substring (6,10) + " " + account.substring (14,18) + "-" + account.substring(18,25);
            }
            if (account != BankNo.value) BankNo.value = account;
        }
  // 添加时切换是否上班课
  $("input[name='Fruit']").click(function(){
        if ($(this).attr('value')=="1") {
            $(this).attr('value','0');
            $(this).attr("chacked",true);
        }else if($(this).attr('value')=="0"){
            $(this).attr('value','1');
            $(this).attr("checked",false);
        }
  });
    //添加新员工API
    // time: 2017/9/23
    $("#save").click(function () {
        addStaff()
    })
    function addStaff(){
          var loginname=$scope.loginname; //登录账号
          var username=$scope.username;
          var roles_name=$("#staffName").text();
          var roles_id=$("#staffIdName").text();
          if(roles_id==""){
              alert("请填写职位");
              return;
          }
          var campus_id=$("#schoolcampus").find("option:selected").val();
          var campus_name=$("#schoolcampus").find("option:selected").text();
          var subject_id=$("#subjectstaught").find("option:selected").val();
          var subject_name=$("#subjectstaught").find("option:selected").text();
          var birthday=$("#modeltimetwo").val();
              birthday=birthday.replace(/-/g,'/');
              birthday=new Date(birthday);
              birthday=birthday.getTime();
              birthday=$filter("date")(birthday, "yyyy-MM-dd");
          var mobile=$scope.mobile;
          var card_bank=$scope.card_bank;
          var card_identification=$scope.card_identification;
          var wechat=$scope.wechat;
          var qq=$scope.qq;
          var email=$scope.email;
          var is_class=$("input[name='Fruit']").attr('value');
          var date_entry=$("#date_entry").val();
              date_entry=date_entry.replace(/-/g,'/');
              date_entry=new Date(date_entry);
              date_entry=date_entry.getTime();
              date_entry=$filter("date")(date_entry, "yyyy-MM-dd");
          var sex=$("#savesex").find("option:selected").val();
         $scope.addStaff={loginname:loginname,username:username,mobile:mobile,sex:sex,birthday:birthday,card_identification:card_identification,card_bank:card_bank,wechat:wechat,qq:qq,email:email,date_entry:date_entry,is_class:is_class,campus_id:campus_id,campus_name:campus_name,roles_id:roles_id,roles_name:roles_name,subject_id:subject_id,subject_name:subject_name}
         console.log($scope.addStaff);
         $http({
           method: 'POST',
           url: '/OA/staff/create',
           data: $.param($scope.addStaff),
           headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
         }).success(function (response){
            if (response.ok== true) {
                $("#studentadd").modal('hide')
                setTimeout(function () {
                    window.location.reload()
                },600)
            };
            })
    }
    $scope.change = function(selectedLimit){
        $scope.page.limit = selectedLimit.limit;
    }
    $scope.pageChanged = function(){
        $scope.page.limit = $scope.selectedLimit.limit;
    }
    $scope.setPage = function (go) {
        $scope.length = Math.ceil($scope.total/$scope.selectedLimit.limit);
        console.log($scope.length);
        if(go > $scope.length){
            $scope.page.pageNo =  $scope.length;
            console.log($scope.length);
        }else{
            $scope.page.pageNo=go;
        }
    };
}]);


